package com.imy.lua.activity.imagecolor;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatCheckBox;

import com.imy.common.event.FloatingEvent;
import com.imy.common.helper.ParamsHelper;
import com.imy.common.util.ALog;
import com.imy.common.util.BitmapUtils;
import com.imy.common.util.ClipboardUtils;
import com.imy.lua.code.ColorCodeMaker;
import com.imy.common.util.ColorUtils;
import com.imy.common.util.FileUtils;
import com.imy.common.util.ImmersionBarUtils;
import com.imy.common.util.ToastUtil;
import com.imy.common.util.UiUtil;
import com.imy.lua.LuaCore;
import com.imy.lua.R;
import com.imy.lua.code.ImageCodeMaker;
import com.imy.lua.dialog.ColorFindDialogTips;
import com.imy.lua.dialog.ColorGetDialog;
import com.imy.lua.dialog.FileNameDialog;
import com.imy.lua.dialog.ImageColorMenuDialog;
import com.imy.lua.helper.color.ImageColorHelper;
import com.imy.lua.helper.opencv.ImageFindHelper;
import com.imy.lua.helper.opencv.ImageWrapper;
import com.imy.lua.helper.properties.PropertiesLoaderHelper;
import com.imy.lua.view.ColorImageToolsView;
import com.imy.lua.view.CropRectView;
import com.imy.lua.view.FindColorView;
import com.imy.lua.view.ManualColorView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

public class ImageColorToolsActivity extends AppCompatActivity {
    private ImageView screenIv;
    private CropRectView cropRectView;
    private ColorImageToolsView toolsView;
    private ManualColorView manualColorView;
    private FindColorView findColorView;
    private TextView logTv;
    private View findTargetView;
    private Bitmap mScreenBitmap;

    public static void start(Context context, String path) {
        //判断下屏幕
        Intent intent;
        int orientation = LuaCore.get().getAccessibilityServiceListener().getOrientation();
        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            intent = new Intent(context, ImageColorToolsActivity.class);
        } else {
            intent = new Intent(context, LandscapeImageColorToolsActivity.class);
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(ParamsHelper.PATH, path);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
            setNotchParams();
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_color_tools);
        screenIv = findViewById(R.id.screen_iv);
        logTv = findViewById(R.id.log_info_tv);
        findTargetView = findViewById(R.id.find_target_view);
        toolsView = findViewById(R.id.color_image_tools_view);
        cropRectView = findViewById(R.id.crop_rect_view);
        cropRectView.setLogTv(logTv);
        ImmersionBarUtils.initFullScreen(this);
        mScreenBitmap = BitmapFactory.decodeFile(getPath());
        screenIv.setImageBitmap(mScreenBitmap);
        initManualView();
        initFindColorView();
        toolsView.setFloatingListener(new ColorImageToolsView.FloatingListener() {
            @Override
            public void onClicked() {
                showMenu();
            }

            @Override
            public void onImageGiveUp() {
                toolsView.hideImageTools();
//                cropRectView.backInit();
                cropRectView.hide();
                logTv.setVisibility(View.INVISIBLE);
                findTargetView.setVisibility(View.GONE);
            }

            @Override
            public void onImageTest() {
                ImageWrapper image = ImageWrapper.ofBitmap(mScreenBitmap);
                cropRectView.measure(0, 0);
                int measuredWidth = cropRectView.getMeasuredWidth();
                int measuredHeight = cropRectView.getMeasuredHeight();
                Bitmap target = Bitmap.createBitmap(mScreenBitmap, (int) cropRectView.getX(),
                        (int) cropRectView.getY(), measuredWidth, measuredHeight);
                Point point = ImageFindHelper.get().findImage(image, ImageWrapper.ofBitmap(target));
                //找到的坐标点
                if (point != null) {
                    int width = target.getWidth();
                    int height = target.getHeight();
                    ViewGroup.LayoutParams layoutParams = findTargetView.getLayoutParams();
                    layoutParams.width = width;
                    layoutParams.height = height;
                    findTargetView.setLayoutParams(layoutParams);
                    findTargetView.setVisibility(View.VISIBLE);
                    findTargetView.setX(point.x);
                    findTargetView.setY(point.y);
                } else {
                    ToastUtil.toast(ImageColorToolsActivity.this, "查找失败，请尝试换个区域截取");
                }

            }

            @Override
            public void onImageSave() {
                FileNameDialog fileNameDialog = new FileNameDialog(ImageColorToolsActivity.this);
                fileNameDialog.show();
                fileNameDialog.getCheckBox().setVisibility(View.VISIBLE);
                fileNameDialog.setFileListener(fileName -> {
                    cropRectView.measure(0, 0);
                    int measuredWidth = cropRectView.getMeasuredWidth();
                    int measuredHeight = cropRectView.getMeasuredHeight();
                    Bitmap target = Bitmap.createBitmap(mScreenBitmap, (int) cropRectView.getX(),
                            (int) cropRectView.getY(), measuredWidth, measuredHeight);
                    fileName = FileUtils.supplyImageSuffix(fileName);
                    String projectRes = PropertiesLoaderHelper.getProjectRes();
                    //获取屏幕分辨率
                    int orientation = LuaCore.get().getAccessibilityServiceListener().getOrientation();
                    String suffix;
                    if (orientation == Configuration.ORIENTATION_PORTRAIT) {
                        suffix = String.valueOf(UiUtil.getDeviceWidth(ImageColorToolsActivity.this));
                    } else {
                        suffix = String.valueOf(UiUtil.getDeviceHeight(ImageColorToolsActivity.this));
                    }
                    String path = projectRes + "/" + suffix;
                    FileUtils.createFileDir(path);
                    boolean b = BitmapUtils.savePath(path + "/" + fileName, target);
                    if (b) {
                        ToastUtil.toast(ImageColorToolsActivity.this, "保存成功");
                    } else {
                        ToastUtil.toast(ImageColorToolsActivity.this, "保存失败");
                    }
                    AppCompatCheckBox checkBox = fileNameDialog.getCheckBox();
                    if (checkBox.isChecked()){
                        //生成找图代码
                        String findImageCode = ImageCodeMaker.getFindImageCode(fileName);
                        ClipboardUtils.setText(ImageColorToolsActivity.this,findImageCode);
                        ToastUtil.toast(ImageColorToolsActivity.this, "复制代码到粘贴板成功");
                    }
                });
            }

            @Override
            public void onColorExit() {
                manualColorView.hide();
            }

            @Override
            public void onColorCodeMake() {
                manualColorView.makeCode(mScreenBitmap);
            }

            @Override
            public void onColorFindExit() {
                findColorView.hide();
            }

            @Override
            public void onColorFindCodeCreate() {
                String currentColor = findColorView.getCurrentColor();
                String findColorInRegionCode = ColorCodeMaker.getFindColorInRegionCode(currentColor,
                        findColorView.getCropX(), findColorView.getCropY(),
                        findColorView.getCropWidth(), findColorView.getCropHeight(), findColorView.getCurrentDim());
                ClipboardUtils.setText(ImageColorToolsActivity.this, findColorInRegionCode);
                ToastUtil.toast(ImageColorToolsActivity.this, "代码已生成至粘贴板");
            }

            @Override
            public void onColorFindTest() {
                String currentColor = findColorView.getCurrentColor();
                if (TextUtils.isEmpty(currentColor)) {
                    ToastUtil.toast(ImageColorToolsActivity.this, "查找的颜色不能为空");
                    return;
                }
                Point color = ImageColorHelper.findColor(mScreenBitmap, currentColor,
                        findColorView.getCropX(), findColorView.getCropY(), findColorView.getCropWidth(),
                        findColorView.getCropHeight(), findColorView.getCurrentDim());
                ALog.i("查找的颜色:" + currentColor);
                if (color != null) {
                    ToastUtil.toast(ImageColorToolsActivity.this, "区域内找色成功");
                    findColorView.showFindPoint(color.x, color.y);
                } else {
                    ToastUtil.toast(ImageColorToolsActivity.this, "区域内找色失败");
                }
            }
        });
    }

    @SuppressLint("NewApi")
    private void setNotchParams() {
        //设置刘海屏
        try {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            getWindow().setAttributes(lp);
        }catch (Exception ignored){

        }
    }

    private void initFindColorView() {
        findColorView = findViewById(R.id.find_color_view);
        findColorView.setColorTouchListener(new FindColorView.ColorTouchListener() {
            @Override
            public void onMove(int x, int y) {
                ALog.i("onMove:" + x);
                int color = ImageColorHelper.getColor(mScreenBitmap, x, y);
                findColorView.showColor(color, x, y);
            }

            @Override
            public void onUp(int x, int y) {
                int color = ImageColorHelper.getColor(mScreenBitmap, x, y);
                ToastUtil.toast(ImageColorToolsActivity.this, "取色成功");
                findColorView.setCurrentColor(color, x, y);
            }
        });
    }

    private void initManualView() {
        manualColorView = findViewById(R.id.manual_color_view);
        manualColorView.setManualListener(new ManualColorView.ManualListener() {
            @Override
            public void onMove(int x, int y) {
                int color = ImageColorHelper.getColor(mScreenBitmap, x, y);
                manualColorView.showColor(color, x, y);
            }

            @Override
            public void onUp(int x, int y) {
                int color = ImageColorHelper.getColor(mScreenBitmap, x, y);
                String s = ColorUtils.integerToHex(color);
                ClipboardUtils.setText(ImageColorToolsActivity.this,
                        s);
                ToastUtil.toast(ImageColorToolsActivity.this, "该点颜色已复制到粘贴板");
            }
        });
    }

    private void showMenu() {
        ImageColorMenuDialog imageColorMenuDialog = new ImageColorMenuDialog(this);
        imageColorMenuDialog.show();
        imageColorMenuDialog.setImageColorMenuListener(new ImageColorMenuDialog.ImageColorMenuListener() {
            @Override
            public void onCropClicked() {
                toolsView.showImageTools();
                //展示cropView
                cropRectView.show();

            }

            @Override
            public void onSavePic() {
                FileNameDialog fileNameDialog = new FileNameDialog(ImageColorToolsActivity.this);
                fileNameDialog.show();
                fileNameDialog.setFileListener(fileName -> {
                    fileName = FileUtils.supplyImageSuffix(fileName);
                    String projectRes = PropertiesLoaderHelper.getProjectRes();
                    boolean b = BitmapUtils.savePath(projectRes + "/" + fileName, mScreenBitmap);
                    if (b) {
                        ToastUtil.toast(ImageColorToolsActivity.this, "保存成功");
                    } else {
                        ToastUtil.toast(ImageColorToolsActivity.this, "保存失败");
                    }
                });
            }

            @Override
            public void onSearchTargetImage() {
                FileNameDialog fileNameDialog = new FileNameDialog(ImageColorToolsActivity.this);
                fileNameDialog.show("请输入图片名(包含后缀)");
                fileNameDialog.setFileListener(fileName -> {
                    String screenFilePath = ImageFindHelper.get().getScreenFilePath();
                    String searchFile = getSearchFile(screenFilePath, fileName);
                    File file = new File(searchFile);
                    if (!file.exists()) {
                        ToastUtil.toast(ImageColorToolsActivity.this,
                                "该机型分辨率下的资源不存在");
                        return;
                    }
                    Bitmap target = BitmapFactory.decodeFile(searchFile);

                    Point point = ImageFindHelper.get().findImage(getPath(),
                            searchFile);
                    //找到的坐标点
                    if (point != null) {
                        int width = target.getWidth();
                        int height = target.getHeight();
                        ViewGroup.LayoutParams layoutParams = findTargetView.getLayoutParams();
                        layoutParams.width = width;
                        layoutParams.height = height;
                        findTargetView.setLayoutParams(layoutParams);
                        findTargetView.setVisibility(View.VISIBLE);
                        findTargetView.setX(point.x);
                        findTargetView.setY(point.y);
                    } else {
                        ToastUtil.toast(ImageColorToolsActivity.this, "查找失败");
                    }
                });
            }

            @Override
            public void onGetOneColor() {
                ColorGetDialog colorGetDialog = new ColorGetDialog(ImageColorToolsActivity.this);
                colorGetDialog.setColorGetListener(new ColorGetDialog.ColorGetListener() {
                    @Override
                    public void onManualColorGet() {
                        //进入手动取点
                        manualColorView.show();
                        toolsView.showColorGet();
                    }

                    @Override
                    public void onGetXYColor(int x, int y) {

                    }
                });

            }

            @Override
            public void onFindColorInRegion() {
                //区域找色
                ColorFindDialogTips colorFindDialogTips = new ColorFindDialogTips(ImageColorToolsActivity.this);
                colorFindDialogTips.show();
                colorFindDialogTips.setInputColorListener((color, v1) -> {
                    findColorView.show();
                    findColorView.setDim(v1);
                    toolsView.showColorFindInRegion();
                    if (!color.equals("")) {
                        findColorView.setCurrentColor(Color.parseColor(color), -1, -1);
                    }

                    //展示区域

                });

            }
        });
    }

    private String getSearchFile(String screen, String fileName) {
        String projectRes = PropertiesLoaderHelper.getProjectRes();


        String path = projectRes + "/" + screen + "/" + fileName;

        if (!path.endsWith(".png")
                && !path.endsWith(".jpg")) {
            String pngPath = path + ".png";
            File file = new File(pngPath);
            if (file.exists()) {
                path = pngPath;
            }
            String jpgPath = path + ".jpg";
            File file1 = new File(jpgPath);
            if (file1.exists()) {
                path = jpgPath;
            }
        }
        return path;
    }

    private String getPath() {
        return getIntent().getStringExtra(ParamsHelper.PATH);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().post(FloatingEvent.create(FloatingEvent.ACTION_SHOW));
    }

    private void hideSystemNav() {
        final View decorView = getWindow().getDecorView();
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        final int flags;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        }else {
            flags=View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        }
        decorView.setSystemUiVisibility(flags);
        decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {
                if (isFinishing()) {
                    return;
                }
                if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                    decorView.setSystemUiVisibility(getShowInputFlags());
                } else if (visibility == 4) {
                    decorView.setSystemUiVisibility(flags);
                }
            }
        });

    }

    private int getShowInputFlags() {
        final int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        return flags;
    }
}
